package cn.edu.sgu.www.pms.util;

import cn.edu.sgu.www.pms.entity.User;
import cn.edu.sgu.www.pms.exception.GlobalException;
import cn.edu.sgu.www.pms.restful.ResponseCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * 获取用户信息的工具类
 * @author 沐雨橙风ιε
 * @version 1.0
 */
public class UserUtils {

    /**
     * 得到Subject对象
     * @return Subject
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取登录的用户信息
     * @return User
     */
    public static User getLoginUser() {
        Subject subject = getSubject();

        if (subject.isAuthenticated()) {
            Object object = subject.getPrincipal();

            return (User) object;
        }

        throw new GlobalException(ResponseCode.FORBIDDEN, "当前没有用户登录，获取用户信息失败...");
    }

    /**
     * 获取登录用户的ID
     * @return String
     */
    public static String getUserId() {
        User user = getLoginUser();

        return user.getId();
    }

    /**
     * 获取登录的用户名
     * @return String
     */
    public static String getLoginUsername() {
        return getLoginUser().getUsername();
    }

}